package com.example.wenqujingdian.activity;

import android.Manifest;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.SystemClock;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.content.FileProvider;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.example.wenqujingdian.ChangeTextViewSpace;
import com.example.wenqujingdian.CustomDialog;
import com.example.wenqujingdian.MarqueeText;
import com.example.wenqujingdian.R;
import com.example.wenqujingdian.adapter.HomeGridViewAdapter;
import com.example.wenqujingdian.adapter.RecommendBookAdapter;
import com.example.wenqujingdian.api.ApiConfig;
import com.example.wenqujingdian.api.Contants;
import com.example.wenqujingdian.api.JsonDataManager;
import com.example.wenqujingdian.bean.BookDetailBean;
import com.example.wenqujingdian.bean.UpDateBean;
import com.example.wenqujingdian.bigdata.BigData;
import com.example.wenqujingdian.conast.AudioKey;
import com.example.wenqujingdian.model.LocalBookBean;
import com.example.wenqujingdian.model.LocalOrgBean;
import com.example.wenqujingdian.model.OrgBean;
import com.example.wenqujingdian.model.RecommendBook;
import com.example.wenqujingdian.model.VideoSectionBean;
import com.example.wenqujingdian.model.VideoSectionChildBean;
import com.example.wenqujingdian.utils.FileUtils;
import com.example.wenqujingdian.utils.GlideImageLoader;
import com.example.wenqujingdian.utils.NetWorkUtils;
import com.example.wenqujingdian.utils.ToastUtil;
import com.example.wenqujingdian.utils.VersionUtils;
import com.vise.xsnow.http.ViseHttp;
import com.vise.xsnow.http.callback.ACallback;
import com.vise.xsnow.http.mode.DownProgress;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import me.jessyan.autosize.AutoSizeCompat;
import me.jessyan.autosize.internal.CustomAdapt;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 首页
 * Create by kxliu on 2018/11/21
 */
public class HomeActivity extends BaseActivity implements BaseQuickAdapter.OnItemClickListener,
        View.OnClickListener, CustomAdapt {
    public static Activity currentActivity;
    private static final String TAG = HomeActivity.class.getSimpleName();
    @BindView(R.id.main_toolbar_title)
    ChangeTextViewSpace mainToolbarTitle;
    @BindView(R.id.main_toolbar)
    Toolbar mainToolbar;
    @BindView(R.id.banner)
    Banner banner;
    @BindView(R.id.home_recycler)
    RecyclerView homeRecycler;
    @BindView(R.id.home_empty)
    TextView homeEmpty;
    //    @BindView(R.id.home_recycler2)
//    RecyclerView homeRecycler2;
    //    @BindView(R.id.marqueeView)
//    MarqueeView marqueeView;
    @BindView(R.id.notice_tv)
    MarqueeText tvNotice;
    @BindView(R.id.marquee_ll)
    LinearLayout marqueeLl;


    private Unbinder bind;
    private boolean networkAvailable;
    //判断网络状态发生变化了再重新加载
    public static boolean networkChanged = false;

    private EditText account;
    private EditText password;
    private AlertDialog alertDialog;

    /**
     * 百度地图
     */
    public LocationClient mLocationClient;
    private HomeGridViewAdapter mAdapter;
    private RecommendBookAdapter recommendBookAdapter;
    private boolean isLocal = false;
    /**
     * 有网数据
     */
    private LocalOrgBean org = null;
    /**
     * 更新的标示
     */
    private boolean flag = true;
    /**
     * 下载apk显示的进度条
     */
    private ProgressDialog progressDialog;
    private CustomDialog dialog;

    //定位flag 判断是否定位过 ,解决重复问题
    private boolean dingWeiFlag = false;

    //点击监听
    long[] mHits = new long[5];

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        currentActivity = this;
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        bind = ButterKnife.bind(this);
        NetWorkUtils.getInstance().startConnectionTrack(this);  //网络追踪开启
        networkAvailable = NetWorkUtils.isNetworkAvailable(this);   //判断是否有网
        mainToolbar.setOnClickListener(new View.OnClickListener() {
            final static int COUNTS = 5;//点击次数
            final static long DURATION = 3 * 1000;//规定有效时间
            long[] mHits = new long[COUNTS];

            @Override
            public void onClick(View v) {
                /**
                 * 实现双击方法
                 * src 拷贝的源数组
                 * srcPos 从源数组的那个位置开始拷贝.
                 * dst 目标数组
                 * dstPos 从目标数组的那个位子开始写数据
                 * length 拷贝的元素的个数
                 */

                System.arraycopy(mHits, 1, mHits, 0, mHits.length - 1);
                //实现左移，然后最后一个位置更新距离开机的时间，如果最后一个时间和最开始时间小于DURATION，即连续5次点击
                mHits[mHits.length - 1] = SystemClock.uptimeMillis();
                if (mHits[0] >= (SystemClock.uptimeMillis() - DURATION)) {
                    // String tips = "您已在[" + DURATION + "]ms内连续点击【" + mHits.length + "】次了！！！";
                    mHits = new long[COUNTS];
                    onToolBarClick();
                }
            }
        });
        initView();
        if (networkAvailable) {
            checkPermission();  //检测权限
            if (org == null) {
                applyMapPermission();   //获取定位前，先获取当前定位信息
            } else {
                setWebData();
            }
            checkUpdate();  //检测更新
        } else {
            isLocal = true;
            checkPermission();
        }
    }

    /**
     * 返回的弹框提示
     */
    public void onToolBarClick() {
        AlertDialog.Builder edit_device = new AlertDialog.Builder(this);
        View view1 = View.inflate(this, R.layout.account_password, null);
        edit_device.setView(view1)  ;
        alertDialog = edit_device.create();
        alertDialog.show();
        account = alertDialog.findViewById(R.id.account);
        password = alertDialog.findViewById(R.id.password);
        View ok = alertDialog.findViewById(R.id.ok);
        ok.setOnClickListener(this);
    }

    /**
     * 检查权限
     */
    private void checkPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            List<String> applyPermissionList = new ArrayList<>();
            if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                applyPermissionList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            }
            if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                applyPermissionList.add(Manifest.permission.READ_EXTERNAL_STORAGE);
            }
            if (applyPermissionList.size() == 0) {
                Contants.SPICIFYPATH = JsonDataManager.getInstance().getSpecificPath(); //加载本地路径
                getNotice();
                if (isLocal) {  //加载本地资源
                    initLocalData();
                }
            } else {
                //请求所缺少的权限。
                String[] requestPermissions = new String[applyPermissionList.size()];
                applyPermissionList.toArray(requestPermissions);
                requestPermissions(requestPermissions, Contants.PERMISSION_STORAGE);
            }
        } else {
            Contants.SPICIFYPATH = JsonDataManager.getInstance().getSpecificPath();
            getNotice();
            if (isLocal) {
                initLocalData();
            }
        }

    }


    /**
     * token校验
     */
    private void checkToken(String imei, String token) {
        ViseHttp.GET("wenqu/check/checkToken/" + imei + "/" + token)
                .tag(TAG)
                .baseUrl(ApiConfig.SERVER_URL)
                .readTimeOut(60)
                //配置写入超时时间，单位秒
                .writeTimeOut(60)
                //配置连接超时时间，单位秒
                .connectTimeOut(60)
                //配置请求失败重试次数
                .retryCount(3)
                //配置请求失败重试间隔时间，单位毫秒
                .retryDelayMillis(1000)
                .request(new ACallback<String>() {
                    @Override
                    public void onSuccess(String data) {
                        Log.d("token校验", data);
                    }

                    @Override
                    public void onFail(int errCode, String errMsg) {
                        Log.d("cordon", "onFail: " + errMsg);
                    }
                });
    }

    /**
     * 设备合法性校验
     */
    private void checkDevice() {
        new Thread(() -> {
            //获取缓存token
            SharedPreferences sp = getSharedPreferences("org", Context.MODE_PRIVATE);
            String token = sp.getString("token", "null");
            //如果为空,先请求token
            if (token.equals("null")) {
                ViseHttp.GET("wenqu/check/getToken/" + getIMEI())
                        .tag(TAG)
                        .baseUrl(ApiConfig.SERVER_URL)
                        .readTimeOut(60)
                        //配置写入超时时间，单位秒
                        .writeTimeOut(60)
                        //配置连接超时时间，单位秒
                        .connectTimeOut(60)
                        //配置请求失败重试次数
                        .retryCount(3)
                        //配置请求失败重试间隔时间，单位毫秒
                        .retryDelayMillis(1000)
                        .request(new ACallback<String>() {
                            @Override
                            public void onSuccess(String data) {
                                checkToken(getIMEI(), data);
                                //写入token
                                SharedPreferences.Editor edit = sp.edit();
                                edit.putString("token", data);
                                edit.apply();
                            }

                            @Override
                            public void onFail(int errCode, String errMsg) {
                                Log.d("cordon", "onFail: " + errMsg);
                            }
                        });
            } else {
                checkToken(getIMEI(), token);
            }
        }).start();

    }

    private void initLocalData() {
        switchView();
        initOrgData();
    }

    /**
     * 加载本地是否有跑马灯文字
     */
    private void getNotice() {
        JsonDataManager.getInstance().getNoticeContent(new JsonDataManager.OnFileExistListener() {
            @Override
            public void onSuccess(String exist) {
                if (!TextUtils.isEmpty(exist)) {
                    marqueeLl.setVisibility(View.VISIBLE);
                    showNotice(exist);
                } else {
                    marqueeLl.setVisibility(View.GONE);
                }
            }

            @Override
            public void onFail(String info) {
                marqueeLl.setVisibility(View.GONE);
            }
        });
    }

    private void showNotice(String notice) {
//        String[] list = notice.split(";");
//        marqueeView.startWithList(Arrays.asList(list));
//        marqueeView.startWithText(notice);
        tvNotice.setText(notice);
    }

    /**
     * 置空数据
     */
    private void switchView() {
        setBanner(null);
        mainToolbarTitle.setText("");
        marqueeLl.setVisibility(View.GONE);
        tvNotice.setText("");
        mAdapter.setNewData(null);
        if (findViewById(R.id.land_tv) == null) {
            recommendBookAdapter.setNewData(null);
        }
    }


    /**
     * 所有权限是否申请成功
     *
     * @param grantResults 权限获得结果的数组
     * @return ture:成功  false:失败
     */
    private boolean isAllPermissionsGranted(int[] grantResults) {
        for (int grantResult : grantResults) {
            if (grantResult == PackageManager.PERMISSION_DENIED) {
                //如果有一个权限返回的是失败,返回false
                return false;
            }
        }
        return true;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == Contants.PERMISSION_STORAGE) {
            if (isAllPermissionsGranted(grantResults)) {
                Contants.SPICIFYPATH = JsonDataManager.getInstance().getSpecificPath();
                if (isLocal) {
                    initLocalData();
                }
            } else {
                ToastUtil.show("读写权限被拒绝");
            }
        } else if (requestCode == Contants.PERMISSION_MAP) {
            //定位权限
            if (isAllPermissionsGranted(grantResults)) {
                initMap();
            } else {
                getOrgData();
                ToastUtil.show("需要获取定位权限");
            }
        }
    }


    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        reFlash();
    }

    //刷新
    public void reFlash() {
        //网络发生变化执行此方法
        if (!networkChanged) {
            Log.i("HomeActivity", "禁止刷新");
            return;
        }
        Log.i("HomeActivity", "调用刷新");
        networkChanged = false;
        isLocal = false;
        networkAvailable = NetWorkUtils.isNetworkAvailable(this);
        if (networkAvailable) {
            checkPermission();
            initNetWorkData();
            if (org == null) {
                applyMapPermission();
            } else {
                setWebData();
            }
        } else {
            isLocal = true;
            if (TextUtils.isEmpty(Contants.SPICIFYPATH)) {
                checkPermission();
            } else {
                initLocalData();
            }
        }
    }

    /**
     * 加载推荐图书资源book65.json
     */
    private void initLocalCommendData() {
        JsonDataManager.getInstance().getLocalBookData(Contants.DANGZHENG, this,
                new JsonDataManager.OnLocalListDataListener<LocalBookBean>() {
                    @Override
                    public void onSuccess(List<LocalBookBean> data) {
                        recommendBookAdapter.setNewData(data);  //设置推荐图书数据
                    }

                    @Override
                    public void onFail(String info) {
                    }
                });
    }

    private void initView() {
        GridLayoutManager manager;
        if (findViewById(R.id.land_tv) != null) {
            //横屏显示
            manager = new GridLayoutManager(this, 6);   //横屏6个
            mAdapter = new HomeGridViewAdapter(R.layout.gridview_item_land, this, /*specificPath,*/ null);
        } else {
            //竖屏显示
            initCommentView();
            manager = new GridLayoutManager(this, 4);//竖屏4个
            mAdapter = new HomeGridViewAdapter(R.layout.gridview_item, this, /*specificPath,*/ null);
        }
        homeRecycler.setLayoutManager(manager);

        mAdapter.setOnItemClickListener(this);  //设置子项点击事件
        homeRecycler.setAdapter(mAdapter);  //RecyclerView设置adapter
    }

    private void initCommentView() {
        RecyclerView homeRecycler2 = findViewById(R.id.home_recycler2);
        homeRecycler2.setLayoutManager(new LinearLayoutManager(this));
        recommendBookAdapter = new RecommendBookAdapter(null, this);
        recommendBookAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if(recommendBookAdapter.getItem(position).getBookTitle().equals("习近平谈治国理政（第一卷简体中文版）")){ //定制模块，跳转webview
                    Intent intent = new Intent(HomeActivity.this, WebViewTopBarActivity.class);
                    intent.putExtra("url", recommendBookAdapter.getItem(position).getBookUrl());
                    intent.putExtra("flag", "1088");
                    startActivity(intent);
                }else {
                    LocalBookBean item = recommendBookAdapter.getItem(position);
                    BookDetailBean bookDetailBean = new BookDetailBean();
                    Intent intent = null;
                    if (!networkAvailable) {
                        intent = new Intent(HomeActivity.this, LocalBookDetailsActivity.class); //本地详情页面
                        intent.putExtra("path", Contants.SPICIFYPATH);
                        bookDetailBean.spic = Contants.SPICIFYPATH + item.getCover();
                    } else {
                        intent = new Intent(HomeActivity.this, BookDetailsActivity.class);  //在线模式详情页面
                        bookDetailBean.spic = item.getCover();
                    }
                    bookDetailBean.id = item.getBookId();
                    bookDetailBean.news_tit = item.getBookTitle();
                    bookDetailBean.author = item.getAuthor();
                    bookDetailBean.jianjie = item.getEdition();
                    bookDetailBean.news_source = item.getEdition();
                    bookDetailBean.url = item.getBookUrl();
                    intent.putExtra("bookDetail", bookDetailBean);  //通过intent将BookDetailBean传递到要跳转的页面
                    startActivity(intent);
                }
            }
        });
        homeRecycler2.setAdapter(recommendBookAdapter);
    }

    /**
     * 判断当前是否授权
     */
    private void initOrgData() {
        boolean isPermission = getSharedPreferences("org", Context.MODE_PRIVATE).getBoolean("isPermission", false);
        if (isPermission) {
            getData();
        } else {
            homeEmpty.setVisibility(View.VISIBLE);
            homeEmpty.setText("设备未授权，首次安装请联系管理员授权，否则请联网授权");
        }

    }

    /**
     * 加载本地org.json资源
     */
    private void getData() {
        JsonDataManager.getInstance().getOrgData(Contants.ORG_JSON,
                this, new JsonDataManager.OnLocalDataListener<LocalOrgBean>() {
                    @Override
                    public void onSuccess(LocalOrgBean data) {
                        mainToolbarTitle.setText(data.getOrgName());    //设置标题
                        if (findViewById(R.id.land_tv) == null) {   //竖屏情况
                            initLocalCommendData(); //加载推荐图书列表资源
                            mainToolbarTitle.setSpacing(10);    //设置字间距
                        }
                        homeEmpty.setVisibility(View.GONE);
                        List<LocalOrgBean.ModuleListBean> moduleList = data.getModuleList();    //模块的数据
                        List<LocalOrgBean.BannerListBean> bannerList = data.getBannerList();    //banner轮播的数据
                        setBanner(bannerList);  //加载banner
                        setFunctionModel(moduleList);   //设置功能模块
                    }

                    @Override
                    public void onFail(String info) {
                        if (homeEmpty == null) {
                            homeEmpty = findViewById(R.id.home_empty);
                        }
                        homeEmpty.setVisibility(View.VISIBLE);
                        homeEmpty.setText(info);
                    }
                });
    }

    /**
     * 申请定位的权限
     */
    private void applyMapPermission() {
        //获得手机系统版本信息是不是大于6.0系统
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            List<String> applyPermissionList = new ArrayList<>();
            //GPS定位
            if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                applyPermissionList.add(Manifest.permission.ACCESS_FINE_LOCATION);
            }

            //用于访问wifi网络信息，wifi信息会用于进行网络定位
            if (checkSelfPermission(Manifest.permission.ACCESS_WIFI_STATE) != PackageManager.PERMISSION_GRANTED) {
                applyPermissionList.add(Manifest.permission.ACCESS_WIFI_STATE);
            }

            //获取运营商信息，用于支持提供运营商信息相关的接口
            if (checkSelfPermission(Manifest.permission.ACCESS_NETWORK_STATE) != PackageManager.PERMISSION_GRANTED) {
                applyPermissionList.add(Manifest.permission.ACCESS_NETWORK_STATE);
            }

            //这个权限用于获取wifi的获取权限，wifi信息会用来进行网络定位
            if (checkSelfPermission(Manifest.permission.CHANGE_WIFI_STATE) != PackageManager.PERMISSION_GRANTED) {
                applyPermissionList.add(Manifest.permission.CHANGE_WIFI_STATE);
            }
            //读取手机当前的状态
            if (checkSelfPermission(Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
                applyPermissionList.add(Manifest.permission.READ_PHONE_STATE);
            }
            //写入扩展存储，向扩展卡写入数据，用于写入离线定位数据
            if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                applyPermissionList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            }
            if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                applyPermissionList.add(Manifest.permission.READ_EXTERNAL_STORAGE);
            }

            if (applyPermissionList.size() == 0) {
                //如果权限都已经有了，就直接调用下载
                initMap();
            } else {
                //请求所缺少的权限。
                String[] requestPermissions = new String[applyPermissionList.size()];
                applyPermissionList.toArray(requestPermissions);
                requestPermissions(requestPermissions, Contants.PERMISSION_MAP);
            }
        } else {
            //不大约6.0不用动态申请权限
            initMap();
        }
    }

    /**
     * 初始化地图定位
     */
    private void initMap() {
        /**
         * 百度地图监听器
         */
        MyLocationListener myListener = new MyLocationListener(this);
        //声明LocationClient类
        mLocationClient = new LocationClient(getApplicationContext());
        //注册监听函数
        mLocationClient.registerLocationListener(myListener);
        LocationClientOption option = new LocationClientOption();
        //设置定位模式
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        //设置返回经纬度坐标类型
//        option.setCoorType("bd09ll");
        //设置是否使用gps
        option.setOpenGps(true);
        //设置是否在stop的时候杀死这个进程
        option.setIgnoreKillProcess(false);
        //mLocationClient为第二步初始化过的LocationClient对象.
        //需将配置好的LocationClientOption对象，通过setLocOption方法传递给LocationClient对象使用
        //更多LocationClientOption的配置，请参照类参考中LocationClientOption类的详细说明
        mLocationClient.setLocOption(option);

        //开始获得位置信息
        mLocationClient.start();
    }

    @Override
    public boolean isBaseOnWidth() {
        return false;
    }

    @Override
    public float getSizeInDp() {
        return 1920;
    }

    /**
     * @describe 百度地图定位
     */
    public class MyLocationListener extends BDAbstractLocationListener {

        private Activity activity;

        public MyLocationListener(Activity activity) {
            this.activity = activity;
        }

        @Override
        public void onReceiveLocation(BDLocation location) {
            if (!dingWeiFlag) {
                dingWeiFlag = true;
                double latitude = location.getLatitude();
                double longitude = location.getLongitude();
                ApiConfig.LATITUDE = String.valueOf(latitude);
                ApiConfig.LONGITUDE = String.valueOf(longitude);
                Log.d("cordon", "onReceiveLocation: LATITUDE:" + ApiConfig.LATITUDE +
                        "/t LONGITUDE:" + ApiConfig.LONGITUDE);
                getOrgData();
            }
        }

    }

    /**
     * 设置功能模块
     *
     * @param moduleList
     */
    private void setFunctionModel(List<LocalOrgBean.ModuleListBean> moduleList) {

        if (moduleList != null && moduleList.size() > 0) {
            mAdapter.setNewData(moduleList);
        }
    }

    /**
     * 设置banner
     *
     * @param bannerList
     */
    private void setBanner(List<LocalOrgBean.BannerListBean> bannerList) {
        if (bannerList != null && bannerList.size() > 0) {
            List<String> images = new ArrayList<>();
            if (!networkAvailable) {
                for (LocalOrgBean.BannerListBean listBean : bannerList) {
                    images.add(Contants.SPICIFYPATH + listBean.getBannerImg());
                }
            } else {
                for (LocalOrgBean.BannerListBean listBean : bannerList) {
                    images.add(listBean.getBannerImg());
                }
            }
            if (banner == null) return;

            //设置banner样式
            banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
            //设置图片加载器
            banner.setImageLoader(new GlideImageLoader());
            //设置图片集合
            banner.setImages(images);
            //设置banner动画效果
            banner.setBannerAnimation(Transformer.Default);
            //设置标题集合（当banner样式有显示title时）
            //设置自动轮播，默认为true
            banner.isAutoPlay(true);
            //设置轮播时间
            banner.setDelayTime(8000);
            //设置指示器位置（当banner模式中有指示器时）
            banner.setIndicatorGravity(BannerConfig.CENTER);
            banner.start();
        }
    }

    private void initNetWorkData() {
        if (homeEmpty.getVisibility() != View.GONE) {
            homeEmpty.setVisibility(View.GONE);
        }
        switchView();
        if (findViewById(R.id.land_tv) == null) {
            getRecommendBooks();
        }
    }

    private void getRecommendBooks() {

        ViseHttp.POST(ApiConfig.RECOMMEND_BOOK)
                .tag(TAG)
                .setHttpCache(true)
                //配置读取超时时间，单位秒
                .readTimeOut(60)
                //配置写入超时时间，单位秒
                .writeTimeOut(60)
                //配置连接超时时间，单位秒
                .connectTimeOut(60)
                //配置请求失败重试次数
                .retryCount(3)
                //配置请求失败重试间隔时间，单位毫秒
                .retryDelayMillis(1000)
                .request(new ACallback<RecommendBook>() {
                    @Override
                    public void onSuccess(RecommendBook data) {
                        List<RecommendBook.DataBean> dataBeans = data.getData();
                        if (dataBeans != null && dataBeans.size() > 0) {
                            List<LocalBookBean> dataList = new ArrayList<>();
                            for (RecommendBook.DataBean book : dataBeans) {
                                LocalBookBean bookBean = new LocalBookBean();
                                bookBean.setBookId(String.valueOf(book.getBookId()));
                                bookBean.setBookTitle(book.getBookTitle());
                                bookBean.setCover(book.getCover());
                                bookBean.setBookUrl(book.getBookUrl());
                                dataList.add(bookBean);
                            }
                            LocalBookBean localBookBean=new LocalBookBean();
                            localBookBean.setBookTitle("习近平谈治国理政（第一卷简体中文版）");
                            localBookBean.setAuthor("习近平");
                            localBookBean.setCover("https://bookbk.img.zhangyue01.com/idc_1/m_1,w_300,h_400/0c12a144/group6/M00/19/C3/CmRae1sh462EQxJ8AAAAADbOW2k489386983.jpg?v=8dV16Hz9&t=CmRae1uq7_Y.");
                            localBookBean.setBookUrl("https://se.zhangyue.com/book/detail?bookId=11668540&bookType=1&appId=f5dbadf8");
                            dataList.add(localBookBean);
                            Collections.reverse(dataList);
                            recommendBookAdapter.setNewData(dataList);
                        }
                    }

                    @Override
                    public void onFail(int errCode, String errMsg) {
                        Log.d("cordon", "onFail: " + errCode + "errMsg:" + errMsg);
                    }
                });
    }

    /**
     * 获取机构信息，判断当前是否授权
     */
    private void getOrgData() {
        Map<String, String> map = new HashMap<>();
        map.put("requestType", "App");
        map.put("timeUnix", "");
        map.put("Sign", "");
        map.put("deviceCoding", "");
        map.put("imei", getIMEI());
        map.put("longitude", ApiConfig.LONGITUDE);
        map.put("latitude", ApiConfig.LATITUDE);

        ViseHttp.POST(ApiConfig.ORG_INFO)
                .tag(TAG)
                .addParams(map)
                .setHttpCache(true)
                //配置读取超时时间，单位秒
                .readTimeOut(60)
                //配置写入超时时间，单位秒
                .writeTimeOut(60)
                //配置连接超时时间，单位秒
                .connectTimeOut(60)
                //配置请求失败重试次数
                .retryCount(3)
                //配置请求失败重试间隔时间，单位毫秒
                .retryDelayMillis(1000)
                .request(new ACallback<OrgBean>() {
                    @Override
                    public void onSuccess(OrgBean orgBean) {
                        getSharedPreferences("org", Context.MODE_PRIVATE).edit().putBoolean("isPermission", false).apply();
                        if (orgBean != null) {
                            org = orgBean.getOrg();
                            if (org == null) {  //如果没有授权
                                ToastUtil.show("该设备未授权");
                                reportDevice();
                                return;
                            }
                            getSharedPreferences("org", Context.MODE_PRIVATE).edit().putBoolean("isPermission", true).apply();
                            //设备在有授权的情况下,检查是否合法
                            checkDevice();
                        }
                        setWebData();
                    }

                    @Override
                    public void onFail(int errCode, String errMsg) {
                        Log.d("cordon", "onFail: " + errCode + "errMsg:" + errMsg);
                    }
                });
    }

    /**
     * 检查更新
     */
    private void checkUpdate() {
        ViseHttp.GET("update/checkVersion")
                .tag(TAG)
                .baseUrl(ApiConfig.SERVER_URL)
                .readTimeOut(60)
                //配置写入超时时间，单位秒
                .writeTimeOut(60)
                //配置连接超时时间，单位秒
                .connectTimeOut(60)
                //配置请求失败重试次数
                .retryCount(3)
                //配置请求失败重试间隔时间，单位毫秒
                .retryDelayMillis(1000)
                .addParam("name", "reader")
                .addParam("version", VersionUtils.getVersionName(HomeActivity.this))
                .request(new ACallback<UpDateBean>() {
                    @Override
                    public void onSuccess(final UpDateBean data) {

                        if (data != null) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    if (data.getData() == null) {
                                        ToastUtil.show("获取更新失败" + data.toString());
                                        return;
                                    }
                                    boolean update = data.getData().getUpdate();
                                    if (update) {
                                        dialog = new CustomDialog(HomeActivity.this);
                                        dialog.setTitle("下载更新", true);
                                        String intro = data.getData().getIntro();
                                        dialog.setMessage(VersionUtils.dialogContent(intro));
                                        dialog.setonCansalLinstener("取消", new CustomDialog.OnCansalLinstener() {
                                            @Override
                                            public void onCancalClick() {
                                                dialog.dismiss();
                                            }
                                        });

                                        dialog.setonConfirmLinstener("确定", new CustomDialog.OnConfirmLinstener() {
                                            @Override
                                            public void onConfirmClick() {
                                                dialog.dismiss();
                                                String url = data.getData().getUrl();
                                                Log.i("下载地址~:", url);
                                                downLoadApk(url);
                                            }
                                        });
                                        dialog.show();
                                    }
                                }
                            });
                        }
                    }

                    @Override
                    public void onFail(int errCode, String errMsg) {
                        Log.d("cordon", "onFail: " + errMsg);
                    }
                });
    }

    private String getDiskCachePath(Context context) {
        String cachePath;
        if ((Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
                || !Environment.isExternalStorageRemovable())
                && context.getExternalCacheDir() != null) {
            cachePath = context.getExternalCacheDir().getPath();
        } else {
            cachePath = context.getCacheDir().getPath();
        }
        return cachePath;
    }

    private void downLoadApk(String url) {
        //  /app/app-debug.apk"
        showDialog();
        final String filePath = getDiskCachePath(getApplicationContext());
        Log.d("下载路径", filePath);
//        final String fileName = url.substring(url.lastIndexOf("/"));
        final String fileName = "app-release.apk";
        Log.d("cordon", "downLoadApk: " + filePath + "\tfielName:" + fileName);
        ViseHttp.DOWNLOAD(url)
                .setRootName(filePath)
                .setFileName(fileName)
                .request(new ACallback<DownProgress>() {
                    @Override
                    public void onSuccess(DownProgress downProgress) {
                        String percent = downProgress.getPercent();
                        long bytes_downloaded = downProgress.getDownloadSize();
                        long bytes_total = downProgress.getTotalSize();
                        int progress = (int) ((bytes_downloaded * 100) / bytes_total);
                        progressDialog.setProgress(progress);
                        if (percent != null && percent.equals("100.00%")) {
                            progressDialog.dismiss();
                            File file = new File(filePath + "/download", fileName);
                            Log.d("cordon", "onSuccess: " + file.exists());
                            if (file.exists()) {
                                progressDialog.dismiss();
                                installApk(file.getPath());
                            }
                        }
                    }

                    @Override
                    public void onFail(int errCode, String errMsg) {
                        Log.i(TAG, "downTxtFile onFail: errCode=" + errCode + " errMsg=" + errMsg);
                        progressDialog.dismiss();
                        if (errCode == 1006) {
                            ToastUtil.show("请求超时");
                        } else {
                            ToastUtil.show("网络请求超时" + errCode);
                            Log.i("下载出错", "downTxtFile onFail: errCode=" + errCode + " errMsg=" + errMsg);
                        }
                    }
                });
    }


    /**
     * 安装apk
     *
     * @param apkPath apk所在路径
     */
    private void installApk(String apkPath) {
        if (TextUtils.isEmpty(apkPath)) return;
        File file = new File(apkPath);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        // 如果没有设置SDCard写权限，或者没有sdcard,apk文件保存在内存中，需要授予权限才能安装
        try {
            String[] command = {"chmod", "777", file.toString()};
            ProcessBuilder builder = new ProcessBuilder(command);
            builder.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //判读版本是否在7.0以上
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //provider authorities
            Uri apkUri = FileProvider.getUriForFile(HomeActivity.this, "com.example.wenqujingdian", file);
            //Granting Temporary Permissions to a URI
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        }

        HomeActivity.this.startActivity(intent);
        HomeActivity.this.finish();
    }

    public void showDialog() {
        progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("下载中...");
        progressDialog.setCancelable(false);
        // 设置进度条参数
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setMax(100);
        // progressDialog.incrementProgressBy(0);
        progressDialog.setIndeterminate(false); // 填false表示是明确显示进度的 填true表示不是明确显示进度的
        progressDialog.show();
    }

    private void setWebData() {
        if(!TextUtils.isEmpty(org.getOrgName())){
            mainToolbarTitle.setText(org.getOrgName()); //设置标题
        }
        if (findViewById(R.id.land_tv) != null) {
            mainToolbarTitle.setSpacing(10);    //设置字间距
        }
        List<LocalOrgBean.ModuleListBean> moduleList = org.getModuleList(); //获取某块的功能集合
        if (moduleList != null && moduleList.size() > 0) {
            setFunctionModel(moduleList);   //adpter填充数据
        }
        List<LocalOrgBean.BannerListBean> bannerList = org.getBannerList();
        setBanner(bannerList);  //加载banner数据
    }

    private String getIMEI() {
        String ANDROID_ID = Settings.System.getString(getContentResolver(), Settings.System.ANDROID_ID);
        return ANDROID_ID;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        bind.unbind();
        NetWorkUtils.getInstance().stopConnectionTrack(this);
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        Intent intent = null;
        LocalOrgBean.ModuleListBean listBean = (LocalOrgBean.ModuleListBean) adapter.getData().get(position);
        String androidLinkAddress = String.valueOf(listBean.getModuleId());
        boolean isExternal = listBean.isIsExternal();

        if (androidLinkAddress.equals("1076")) {
            listBean = (LocalOrgBean.ModuleListBean) adapter.getData().get(position);
            intent = new Intent(this, FunctionModelActivity.class);
            intent.putExtra("title", listBean.getModuleName());
            intent.putExtra("filename", Contants.BOOK3D);
            startActivity(intent);
        } else if (networkAvailable && androidLinkAddress.equals("1075")) {//党史学习
            intent = new Intent(this, BookSortListActivity.class);
            intent.putExtra("typeId", 207);
            intent.putExtra("typeName", "党史学习");
            startActivity(intent);
        } else if (isExternal) {
            intent = new Intent(this, WebView2Activity.class);
            String linkAddress = listBean.getLinkAddress();
            intent.putExtra("linkAddress", linkAddress);
            startActivity(intent);
        } else if (networkAvailable && androidLinkAddress.equals("1")) { //云图书
            intent = new Intent(this, CloundBookActivity.class);
            startActivity(intent);
        } else if (androidLinkAddress.equals("2")) {//2:听书
            intent = new Intent(this, AudioClassActivity.class);
            intent.putExtra("flag", "听书");
            startActivity(intent);
        } else if (androidLinkAddress.equals("3")) {//3:期刊
            //初始化语音key
            getAudioKey();
            JsonDataManager.getInstance().getLocalBookData2(Contants.LOCAL_QIKAN_JSON, currentActivity,
                    new JsonDataManager.OnLocalListDataListener<LocalBookBean>() {
                        @Override
                        public void onSuccess(List<LocalBookBean> data) {
                            List<LocalBookBean> books = data;
                            ArrayList<LocalBookBean> bookIdBeanList = new ArrayList<>();
                            for (int i = 0; i < books.size(); i++) {
                                LocalBookBean booksBean = books.get(i);
                                bookIdBeanList.add(booksBean);
                            }
                            BigData.bookByClassIdList = bookIdBeanList;
                            Intent intent = new Intent(currentActivity, BookClassListActivity.class);
                            //改用静态成员来绕过页面数据传递大小限制
                            intent.putExtra("typeName", "期刊");
                            intent.putExtra("path", Contants.SPICIFYPATH);
                            intent.putExtra("type", "netWork");
                            startActivity(intent);
                        }

                        @Override
                        public void onFail(String info) {
                            ToastUtil.show("读取失败...");
                        }
                    });
//            intent = new Intent(this, WebViewActivity3.class);
//            intent.putExtra("url", "http://vertical.591adb.com/wqjd.html");
//            startActivity(intent);
        } else if (androidLinkAddress.equals("4")) {//4:报纸
            getAudioKey();
            intent = new Intent(this, PaperHomeActivity.class);
            startActivity(intent);
        } else if (androidLinkAddress.equals("5")) {// 5:视频
            intent = new Intent(this, VideoHomeActivity.class);
            intent.putExtra("flag", "视频");
            startActivity(intent);
        } else if (androidLinkAddress.equals("6")) {//6:微课
            intent = new Intent(this, BrowserActivity.class);
            intent.putExtra("url", "http://wqjd.wowxue.com/");
            startActivity(intent);
        } else if (networkAvailable && androidLinkAddress.equals("7")) {//7:国学新读
            intent = new Intent(this, BookModelActivity.class);
            intent.putExtra("title", listBean.getModuleName());
            intent.putExtra("classId", listBean.getClassId());
            startActivity(intent);
        } else if (!networkAvailable && androidLinkAddress.equals("7")) {
            listBean = (LocalOrgBean.ModuleListBean) adapter.getData().get(position);
            intent = new Intent(this, FunctionModelActivity.class);
            intent.putExtra("title", listBean.getModuleName());
            intent.putExtra("filename", Contants.GUOXUE);
            startActivity(intent);
        } else if (androidLinkAddress.equals("8")) {//8:纠错宝
            intent = new Intent(this, WebView2Activity.class);
            intent.putExtra("flag", "23");
            startActivity(intent);
        } else if (networkAvailable && androidLinkAddress.equals("9")) {//9:新教育
            intent = new Intent(this, BookModelActivity.class);
            intent.putExtra("title", listBean.getModuleName());
            intent.putExtra("classId", listBean.getClassId());
            startActivity(intent);
        } else if (!networkAvailable && androidLinkAddress.equals("9")) {
            listBean = (LocalOrgBean.ModuleListBean) adapter.getData().get(position);
            intent = new Intent(this, FunctionModelActivity.class);
            intent.putExtra("title", listBean.getModuleName());
            intent.putExtra("filename", Contants.XINJIAOYU);
            startActivity(intent);
        } else if (networkAvailable && androidLinkAddress.equals("10")) {//10:健康养生
            intent = new Intent(this, BookModelActivity.class);
            intent.putExtra("title", listBean.getModuleName());
            intent.putExtra("classId", listBean.getClassId());
            startActivity(intent);

        } else if (!networkAvailable && androidLinkAddress.equals("10")) {
            listBean = (LocalOrgBean.ModuleListBean) adapter.getData().get(position);
            intent = new Intent(this, FunctionModelActivity.class);
            intent.putExtra("title", listBean.getModuleName());
            intent.putExtra("filename", Contants.JIANGKANG);
            startActivity(intent);
        } else if (networkAvailable && androidLinkAddress.equals("11")) {//11:党政专题
            intent = new Intent(this, BookModelActivity.class);
            intent.putExtra("title", listBean.getModuleName());
            intent.putExtra("classId", listBean.getClassId());
            startActivity(intent);
        } else if (!networkAvailable && androidLinkAddress.equals("11")) {
            listBean = (LocalOrgBean.ModuleListBean) adapter.getData().get(position);
            intent = new Intent(this, FunctionModelActivity.class);
            intent.putExtra("title", listBean.getModuleName());
            intent.putExtra("filename", Contants.DANGZHENG);
            startActivity(intent);
        } else if (!networkAvailable && androidLinkAddress.equals("1075")) {
            listBean = (LocalOrgBean.ModuleListBean) adapter.getData().get(position);
            intent = new Intent(this, FunctionModelActivity.class);
            intent.putExtra("title", listBean.getModuleName());
            intent.putExtra("filename", Contants.DANGSHI);
            startActivity(intent);
        } else if (networkAvailable && androidLinkAddress.equals("12")) {//12:创业创新
            intent = new Intent(this, BookModelActivity.class);
            intent.putExtra("title", listBean.getModuleName());
            intent.putExtra("classId", listBean.getClassId());
            startActivity(intent);
        } else if (!networkAvailable && androidLinkAddress.equals("12")) {
            listBean = (LocalOrgBean.ModuleListBean) adapter.getData().get(position);
            intent = new Intent(this, FunctionModelActivity.class);
            intent.putExtra("title", listBean.getModuleName());
            intent.putExtra("filename", Contants.CHUANGYE);
            startActivity(intent);
            //本地图书
        } else if ((androidLinkAddress.equals("1003") || androidLinkAddress.equals("1"))) {
            intent = new Intent(this, LocalBooksActivity.class);
            intent.putExtra("title", listBean.getModuleName());
            startActivity(intent);
        } else if (androidLinkAddress.equals("1009")) {//本地视频
            intent = new Intent(this, VideoLocalHomeActivity.class);
            intent.putExtra("title", "本地视频");
            startActivity(intent);

        } else if (androidLinkAddress.equals("1010")) {//本地音频
            intent = new Intent(this, AudioLocalClassActivity.class);
            intent.putExtra("title", "本地音频");
            startActivity(intent);
        } else if (androidLinkAddress.equals("1038")) {//艺术
            intent = new Intent(this, PaintActivity.class);
            intent.putExtra("title", "艺术");
            startActivity(intent);
        } else if (androidLinkAddress.equals("1044")) { //国学启蒙
            intent = new Intent(this, VideoMoreActivity.class);
            Bundle bundle = new Bundle();
            bundle.putString("title", "国学启蒙");
            bundle.putInt("id", 119);
            intent.putExtras(bundle);
            startActivity(intent);
        } else if (androidLinkAddress.equals("1045")) { //绘本
            intent = new Intent(this, BookModelActivity.class);
            intent.putExtra("title", listBean.getModuleName());
            intent.putExtra("classId", 194);
            startActivity(intent);
        } else if (androidLinkAddress.equals("1046")) { //科普知识
            intent = new Intent(this, VideoMoreActivity.class);
            Bundle bundle = new Bundle();
            bundle.putString("title", "科普知识");
            bundle.putInt("id", 70);
            intent.putExtras(bundle);
            startActivity(intent);

        } else if (androidLinkAddress.equals("1047")) { //美术
            intent = new Intent(this, VideoMoreActivity.class);
            Bundle bundle = new Bundle();
            bundle.putString("title", "美术");
            bundle.putInt("id", 71);
            intent.putExtras(bundle);
            startActivity(intent);

        } else if (androidLinkAddress.equals("1048")) { //书法
            intent = new Intent(this, VideoMoreActivity.class);
            Bundle bundle = new Bundle();
            bundle.putString("title", "书法");
            bundle.putInt("id", 83);
            intent.putExtras(bundle);
            startActivity(intent);

        } else if (androidLinkAddress.equals("1049")) { //唐诗宋词
            intent = new Intent(this, VideoMoreActivity.class);
            Bundle bundle = new Bundle();
            bundle.putString("title", "唐诗宋词");
            bundle.putInt("id", 11);
            intent.putExtras(bundle);
            startActivity(intent);

        } else if (androidLinkAddress.equals("1051")) { //幼儿教育
            intent = new Intent(this, VideoMoreActivity.class);
            Bundle bundle = new Bundle();
            bundle.putString("title", "幼儿教育");
            bundle.putInt("id", 33);
            intent.putExtras(bundle);
            startActivity(intent);

        } else if (androidLinkAddress.equals("1050")) { //音乐
            intent = new Intent(this, AudioMoreActivity.class);
            Bundle bundle = new Bundle();
            bundle.putString("title", "音乐");
            bundle.putInt("id", 117);
            intent.putExtras(bundle);
            startActivity(intent);
        } else if (androidLinkAddress.equals("1052")) { //手机端APP扫码下载
            intent = new Intent(this, DownloadActivity.class);
            //intent.putExtra("flag", "1");
            //intent.putExtra("url", listBean.getLinkAddress());
            startActivity(intent);
        } else if (androidLinkAddress.equals("1078")) { //手机端APP扫码下载代注册
            intent = new Intent(this, ClientRegActivity.class);
            startActivity(intent);
        } else if (androidLinkAddress.equals("1026")) {//两学一做
            intent = new Intent(this, WebView2Activity.class);
            intent.putExtra("flag", "2");
            startActivity(intent);
        } else if (androidLinkAddress.equals("1036")) { //企业文化
            startActivity(new Intent(this, CustomerShowActivity.class));
        } else if (androidLinkAddress.equals("1053")) {//法律图书
            intent = new Intent(this, BookSortListActivity.class);
            intent.putExtra("typeId", 32);
            intent.putExtra("typeName", "法律图书");
            startActivity(intent);
        } else if (androidLinkAddress.equals("1093")&&networkAvailable) {//新书推荐
            intent = new Intent(this, BookSortListActivity.class);
            intent.putExtra("typeId", 199);
            intent.putExtra("typeName", "新书推荐");
            startActivity(intent);
        } else if (androidLinkAddress.equals("1066")) {//医药图书
            intent = new Intent(this, BookSortListActivity.class);
            intent.putExtra("typeId", 53);
            intent.putExtra("typeName", "医药图书");
            startActivity(intent);
        } else if (androidLinkAddress.equals("1057")) {//知网
            intent = new Intent(this, WebView2Activity.class);
            intent.putExtra("flag", "1057");
            startActivity(intent);
        } else if (androidLinkAddress.equals("1058")) {//百度
            intent = new Intent(this, WebView2Activity.class);
            intent.putExtra("flag", "1058");
            startActivity(intent);
        } else if (androidLinkAddress.equals("10001")) {//绘本  本地
            JsonDataManager.getInstance().getLocalBookData(Contants.LOCAL_BOOK_JSON, this,
                    new JsonDataManager.OnLocalListDataListener<LocalBookBean>() {
                        @Override
                        public void onSuccess(List<LocalBookBean> data) {
                            List<LocalBookBean> books = data;
                            ArrayList<LocalBookBean> bookIdBeanList = new ArrayList<>();
                            for (int i = 0; i < books.size(); i++) {
                                LocalBookBean booksBean = books.get(i);
                                String bookId = booksBean.getClassId();
                                if (bookId != null) {
                                    if (!bookId.equals("112")) {
                                        continue;
                                    }
                                    bookIdBeanList.add(booksBean);
                                }
                            }
                            BigData.bookByClassIdList = bookIdBeanList;
                            Intent intent = new Intent(HomeActivity.this, BookClassListActivity.class);
                            //改用静态成员来绕过页面数据传递大小限制
                            intent.putExtra("typeName", "绘本");
                            intent.putExtra("path", Contants.SPICIFYPATH);
                            startActivity(intent);
                        }

                        @Override
                        public void onFail(String info) {
                            ToastUtil.show("读取失败...");
                        }
                    });

        } else if (androidLinkAddress.equals("10002")) {//唐诗宋词  本地
            intent = new Intent(this, VideoLocalMoreActivity.class);
            Bundle bundle = new Bundle();
            bundle.putString("title", "唐诗宋词");
            bundle.putInt("id", 11);
            bundle.putString("path", JsonDataManager.getInstance().getSpecificPath());
            intent.putExtras(bundle);
            startActivity(intent);
        } else if (androidLinkAddress.equals("10003")) {//国学启蒙  本地
            intent = new Intent(this, VideoLocalMoreActivity.class);
            Bundle bundle = new Bundle();
            bundle.putString("title", "国学启蒙");
            bundle.putInt("id", 119);
            bundle.putString("path", JsonDataManager.getInstance().getSpecificPath());
            intent.putExtras(bundle);
            startActivity(intent);
        } else if (androidLinkAddress.equals("10004")) {//科普知识  本地
            intent = new Intent(this, VideoLocalMoreActivity.class);
            Bundle bundle = new Bundle();
            bundle.putString("title", "科普知识");
            bundle.putInt("id", 70);
            bundle.putString("path", JsonDataManager.getInstance().getSpecificPath());
            intent.putExtras(bundle);
            startActivity(intent);
        } else if (androidLinkAddress.equals("10005")) {//书法  本地
            intent = new Intent(this, VideoLocalMoreActivity.class);
            Bundle bundle = new Bundle();
            bundle.putString("title", "书法");
            bundle.putInt("id", 83);
            bundle.putString("path", JsonDataManager.getInstance().getSpecificPath());
            intent.putExtras(bundle);
            startActivity(intent);
        } else if (androidLinkAddress.equals("10006")) {//美术  本地
            intent = new Intent(this, VideoLocalMoreActivity.class);
            Bundle bundle = new Bundle();
            bundle.putString("title", "美术");
            bundle.putInt("id", 71);
            bundle.putString("path", JsonDataManager.getInstance().getSpecificPath());
            intent.putExtras(bundle);
            startActivity(intent);
        } else if (androidLinkAddress.equals("1085")) { //学习路上
            JsonDataManager.getInstance().getLocalBookData2(Contants.LOCAL_XXLS_JSON, this,
                    new JsonDataManager.OnLocalListDataListener<LocalBookBean>() {
                        @Override
                        public void onSuccess(List<LocalBookBean> data) {
                            List<LocalBookBean> books = data;
                            ArrayList<LocalBookBean> bookIdBeanList = new ArrayList<>();
                            for (int i = 0; i < books.size(); i++) {
                                LocalBookBean booksBean = books.get(i);
                                bookIdBeanList.add(booksBean);
                            }
                            BigData.bookByClassIdList = bookIdBeanList;
                            Intent intent = new Intent(HomeActivity.this, BookClassListActivity.class);
                            //改用静态成员来绕过页面数据传递大小限制
                            intent.putExtra("typeName", "学习路上");
                            intent.putExtra("path", Contants.SPICIFYPATH);
                            intent.putExtra("type", "netWork");
                            startActivity(intent);
                        }
                        @Override
                        public void onFail(String info) {
                            ToastUtil.show("读取失败...");
                        }
                    });
        }else if (networkAvailable && androidLinkAddress.equals("1096")) {// 经济金融
            intent = new Intent(this, BookSortListActivity.class);
            intent.putExtra("typeId", 210);
            intent.putExtra("typeName", "经济金融");
            startActivity(intent);
        } else if (androidLinkAddress.equals("1093")&&networkAvailable==false) {//新书推荐
            listBean = (LocalOrgBean.ModuleListBean) adapter.getData().get(position);
            intent = new Intent(this, FunctionModelActivity.class);
            intent.putExtra("title", listBean.getModuleName());
            intent.putExtra("filename", Contants.LOCAL_XSTJ_JSON);
            startActivity(intent);
        }else if(networkAvailable&&androidLinkAddress.equals("1105")){
            intent = new Intent(this, WebView2Activity.class);
            intent.putExtra("flag", "1105");
            startActivity(intent);
        }else if(networkAvailable&&androidLinkAddress.equals("1106")){
            intent = new Intent(this, WebView2Activity.class);
            intent.putExtra("flag", "1106");
            startActivity(intent);
        }else {
            ToastUtil.show("该模块暂无开发，敬请期待");
        }
    }


    /**
     * 退出账号密码
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onClick(View v) {
        alertDialog.dismiss();
        new Thread(new Runnable() {
            @Override
            public void run() {
                runOnUiThread(() -> {
                    if (account.getText().toString().trim().equals("wqjd") &&
                            password.getText().toString().trim().equals("123456")) {
                        Intent intent = new Intent(HomeActivity.this, AdminActivity.class);
                        intent.putExtra("deviceCode", getIMEI());
                        startActivity(intent);
                        finish();
                        ToastUtil.show("密码正确");
                    } else {
                        ToastUtil.show("密码错误");
                    }
                });
            }
        }).start();
    }

    //提交登录信息
    public void reportDevice() {
        dialog = new CustomDialog(HomeActivity.this);
        dialog.setTitle("注册提示", true);
        dialog.setMessage(VersionUtils.dialogContent("您的设备未注册,是否提交信息到后台?"));
        dialog.setonCansalLinstener("取消", new CustomDialog.OnCansalLinstener() {
            @Override
            public void onCancalClick() {
                dialog.dismiss();
            }
        });

        dialog.setonConfirmLinstener("确定", new CustomDialog.OnConfirmLinstener() {
            @Override
            public void onConfirmClick() {
                dialog.dismiss();
                Intent intent = new Intent(HomeActivity.this, AdminActivity.class); //跳转授权界面
                intent.putExtra("deviceCode", getIMEI());
                startActivity(intent);
                finish();
            }
        });
    }

    //初始化语音key
    private void getAudioKey() {
        ViseHttp.GET("/wenqu/getAudioKey")
                .baseUrl(ApiConfig.SERVER_URL)
                .tag("语音key获取")
                .request(new ACallback<String>() {
                    @Override
                    public void onSuccess(String result) {
                        // NiceDialogUtils.dismissNiceDialog();
                        AudioKey.key = result;
                        Log.i("语音key获取", "onSuccess: result=" + AudioKey.key);
                    }

                    @Override
                    public void onFail(int errCode, String errMsg) {
                        ToastUtil.showToast("errCode=" + errCode + " errMsg=" + errMsg);
                    }
                });
    }
}
